package com.example.myapplication.activity;

import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.provider.MediaStore;
import android.system.Os;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.CompoundButton;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.app.AppCompatDelegate;
import androidx.preference.Preference;
import androidx.preference.PreferenceManager;

import com.example.myapplication.R;
import com.example.myapplication.utils.GetPictureUtils;
import com.example.myapplication.utils.SharedPreferencesUtil;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import android.provider.Settings;
import android.view.WindowManager;
import android.os.Build;
import android.os.Build.VERSION_CODES;
import android.widget.TextView;
import android.widget.Toast;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import okhttp3.Call;

public class activity_setting extends AppCompatActivity {
    String  original;
    Button button;
    EditText editTextTextPassword2;

    EditText  newPassword1;
    String    new1 ;
    EditText  newPassword2;
    String    new2;
    EditText   phone;
     static   int mark=0;
    String newPhone;
    String originalName;
    private TextView tv_mian_bar;
    private Button tv_back;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_setting);

        //去除默认标题栏
        ActionBar actionBar=getSupportActionBar();
        if(actionBar!=null){
            actionBar.hide();
        }

        init();

  if(mark==0){
     Permission.checkPermission(this);
      mark++;
  }


    }
 @Override
      protected void onStart() {
         super.onStart();

    }
   /* @Override
    protected void onRestart() {
        super.onRestart();
        Log.d("FirstActivity", "onRestart");
    }*/

    private static final int REQUEST_IMAGE_CAPTURE = 1;
    @Override
    protected void onResume() {
        super.onResume();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (!Settings.System.canWrite(this)) {
                Intent intent = new Intent(Settings.ACTION_MANAGE_WRITE_SETTINGS);
                intent.setData(Uri.parse("package:" + getPackageName()));
                startActivity(intent);
            }
        }
    }

    private  void openCamera() {
        Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
            startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
            // 处理从摄像机返回的照片数据，例如显示照片预览或保存照片
            Bundle extras = data.getExtras();
            Bitmap imageBitmap = (Bitmap) extras.get("data");
            GetPictureUtils.setImageBitmap(imageBitmap);
            // 在此处进行进一步的处理
            ImageView photoPreviewImageView = findViewById(R.id.imageView5);
            photoPreviewImageView.setImageBitmap(GetPictureUtils.getImageBitmap());
        }
    }
    @Override
    public void onRequestPermissionsResult(
            int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == Permission.REQUEST_CODE) {
            for (int grantResult : grantResults) {
                if (grantResult != PackageManager.PERMISSION_GRANTED) {
                    Log.e("Permission","授权失败！");
                    // 授权失败，退出应用
                    this.finish();
                    return;
                }
            }
        }
    }
    private void init() {

        SharedPreferences sp=getSharedPreferences("loginInfo", MODE_PRIVATE);
        originalName=sp.getString("loginUserName","");


        tv_mian_bar = (TextView) findViewById(R.id.tv_main_title);
        tv_mian_bar.setText("Setting");

        tv_back = (Button) findViewById(R.id.tv_back);

        //返回按钮监听
        tv_back.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                activity_setting.this.finish();
            }
        });
        newPassword2=(EditText) findViewById(R.id.editTextTextPassword4);
        newPassword1=(EditText) findViewById(R.id.editTextTextPassword3);
        button=findViewById(R.id.button);
        phone=(EditText) findViewById(R.id.newName);
        editTextTextPassword2=(EditText) findViewById(R.id.editTextTextPassword2);
        //修改密码事件
       /* button.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {


                if (original==null) {
                    Toast.makeText(activity_setting.this, "请输入原密码", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (new1==null) {
                    Toast.makeText(activity_setting.this, "请输入新密码", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (new2==null) {
                    Toast.makeText(activity_setting.this, "请再输入新密码", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (!new1.equals(new2)) {
                    Toast.makeText(activity_setting.this, "两次输入的密码不一致", Toast.LENGTH_SHORT).show();
                    return;
                }

                    OkHttpUtils
                        .post()
                        .url("http://121.36.92.128:8086/changePassword")
                        .addParams("oldPassword",original)
                        .addParams("newPassword", new1)
                        .addParams("username",originalName)
                        .build()
                        .execute(new StringCallback() {
                            @Override
                            public void onError(Call call, Exception e, int i) {
                                System.out.println(e.toString());
                            }
                            @Override
                            public void onResponse(String response, int i) {

                                if (response.equals("true")) {
                                   Toast.makeText(activity_setting.this, "修改成功", Toast.LENGTH_SHORT).show();
                                    return;
                                }  else {
                                    Toast.makeText(activity_setting.this, "原密码错误", Toast.LENGTH_SHORT).show();
                                }
                            }
                        });

                }


        });*/
        button.setOnClickListener( new View.OnClickListener(){

            @Override
            public void onClick(View arg0){


                original = editTextTextPassword2.getText().toString().trim();
                new1 = newPassword1.getText().toString().trim();
                new2 = newPassword2.getText().toString().trim();

                String regEx = "(?=.*[A-Za-z])(?=.*\\d)[A-Za-z\\d]{6,20}$";
                Pattern pattern = Pattern.compile(regEx);

                if(original == null) {
                    Toast.makeText(activity_setting.this, "请输入原密码", Toast.LENGTH_SHORT).show();
                    return;
                }

                if(new1 == null) {
                    Toast.makeText(activity_setting.this, "请输入新密码", Toast.LENGTH_SHORT).show();
                    return;
                }
                if(new2 == null){
                    Toast.makeText(activity_setting.this, "请确认密码", Toast.LENGTH_SHORT).show();
                    return;
                }
                if(!new1.equals(new2))
                {
                    Toast.makeText(activity_setting.this, "输入密码不一致", Toast.LENGTH_SHORT).show();
                    return;
                }

                Matcher matcher = pattern.matcher(new1);
               if(matcher.matches()){
                    OkHttpUtils
                            .post()
                            .url("http://121.36.92.128:8086/changePassword")
                            .addParams("oldPassword", original)
                            .addParams("newPassword",new1)
                            .addParams("username",originalName)
                            .build()
                            .execute(new StringCallback() {
                                @Override
                                public void onError(Call call, Exception e, int i) {
                                    System.out.println(e.toString());
                                }

                                @Override
                                public void onResponse(String response, int i) {
                                    if (response.equals("false")) {
                                        Toast.makeText(activity_setting.this, "原密码错误", Toast.LENGTH_SHORT).show();

                                    }
                                    if(response.equals("true")){
                                        Toast.makeText(activity_setting.this, "修改成功", Toast.LENGTH_SHORT).show();


                                    }
                                }
                            });
                }else{
                    Toast.makeText(activity_setting.this, "密码必须同时包含数字与字母,且长度为 6-20位", Toast.LENGTH_SHORT).show();
                }
            }
        });
        //修改手机号
        Button button8=findViewById(R.id.button2);
        button8.setOnClickListener(new View.OnClickListener(){

            @Override
            public void onClick(View arg0){
                newPhone=phone.getText().toString().trim();
                OkHttpUtils
                        .post()
                        .url("http://121.36.92.128:8086/changePhone")
                        .addParams("phone", newPhone)
                        .addParams("username",originalName)
                        .build()
                        .execute(new StringCallback() {
                            @Override
                            public void onError(Call call, Exception e, int i) {
                                System.out.println(e.toString());
                            }

                            @Override
                            public void onResponse(String response, int i) {
                                if (response.equals("false")) {
                                    Toast.makeText(activity_setting.this, "修改失败", Toast.LENGTH_SHORT).show();

                                }
                                if(response.equals("true")){
                                    Toast.makeText(activity_setting.this, "修改成功", Toast.LENGTH_SHORT).show();


                                }
                            }
                        });
            }
        });
        //拍照事件
        Button buttonCamera =findViewById(R.id.button6);
        buttonCamera.setOnClickListener(v -> {
           /*   SharedPreferences.Editor editor=sp.edit();
              editor.putBoolean("isLogin",false);
              editor.putString("loginUserName","");
              editor.commit();
              Intent intent = new Intent(activity_setting.this, activity_login.class);
              startActivity(intent);
              // TODO Auto-generated method stub
              activity_setting.this.finish();*/
          openCamera();

          });
        Button button1 = (Button) findViewById(R.id.button_day);
        button1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getDelegate().setLocalNightMode(AppCompatDelegate.MODE_NIGHT_NO);
//不加recreate();也行，要是切换不成功，再加这行试试
                recreate();
            }
        });

        Button button2 = (Button) findViewById(R.id.button_night);
        button2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                getDelegate().setLocalNightMode(AppCompatDelegate.MODE_NIGHT_YES);
//不加recreate();也行，要是切换不成功，再加这行试试
                recreate();
            }
        });

      SeekBar brightnessSeekBar = findViewById(R.id.light_seekBar);
        brightnessSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener()

        {

            public void onProgressChanged (SeekBar seekBar,int progress, boolean fromUser){
                // 在滑动过程中，可以在此处更新亮度
                int brightnessValue = (int) (progress * 2.55); // 将0-100的进度值映射到0-255范围内的亮度值
                setScreenBrightness(brightnessValue);
            }


            public void onStartTrackingTouch (SeekBar seekBar){
                // 当开始滑动SeekBar时调用，可以在此处执行需要的操作
                System.out.println("开始调整屏幕亮度");
            }


            public void onStopTrackingTouch (SeekBar seekBar){
                // 当停止滑动SeekBar时调用，可以在此处执行需要的操作
                System.out.println("停止调整屏幕亮度");
                int progress = seekBar.getProgress();
                System.out.println("当前进度：" + progress);
            }

            private void setScreenBrightness ( int brightnessValue){
                Settings.System.putInt(getContentResolver(), Settings.System.SCREEN_BRIGHTNESS_MODE, Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL);
                Settings.System.putInt(getContentResolver(), Settings.System.SCREEN_BRIGHTNESS, brightnessValue);
                WindowManager.LayoutParams layoutParams = getWindow().getAttributes();
                layoutParams.screenBrightness = brightnessValue / 255f;
                getWindow().setAttributes(layoutParams);
            }

        });

    }
}
